package com.goods.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goods.business.mapper.*;
import com.goods.business.service.InStockService;
import com.goods.common.model.business.*;
import com.goods.common.model.system.User;
import com.goods.common.vo.business.*;
import com.goods.common.vo.system.PageVO;
import com.goods.system.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author XiaoHong
 * @description
 * @date 2022/2/17
 */

/*
*    Example example = new Example(InStockInfo.class);
*
*       //第一种：构建内部查询条件对象。
          Example.Criteria criteria = example.createCriteria();
        * criteria.andequalsTO(),后面再继续追加用andEqualsTo/orEqualsTo 等等
        *  第二种  example.and或者or  将每一个条件对象连接。
        * example.and(example.createCriteria().andEqualsTo())
        *
*
* */

/*
* 使用pageinfo对象获取总数
*
* */
@Service
public class InStockServiceImpl implements InStockService {
    @Autowired
    private InStockMapper inStockMapper;

    @Autowired
    private SupplierMapper supplierMapper;
    //入库单（入库记录）数据分页列表展示

    @Override
    public PageVO<InStockVO> findInStockList(InStockVO inStockVO, Integer pageNum, Integer pageSize) {
        /*
         * InStockVO(id=null, inNum=231232, type=2, operator=null, supplierId=null,
         * supplierName=null, createTime=null, modified=null, productNumber=null, remark=null, products=[],
         *  status=0, startTime=Thu Feb 03 00:00:00 CST 2022, endTime=Fri Mar 04 00:00:00 CST 2022,
         *  name=null, address=null, email=null, phone=null, sort=null, contact=null)
         *入库类型、入库单号、入库单状态以及入库时间区间
         * */

//        //开启分页
        PageHelper.startPage(pageNum, pageSize);
//        //设置查询对象  其实有点相似  new QueryWrapper
        Example example = new Example(InStock.class);
//        //创建查询条件
        Example.Criteria criteria = example.createCriteria();
//        //入库类型
        if (!StringUtils.isEmpty(inStockVO.getType())) {
            criteria.andEqualTo("type", inStockVO.getType());
        }

        //入库单号
        if (!StringUtils.isEmpty(inStockVO.getInNum())) {
            criteria.andEqualTo("inNum", inStockVO.getInNum());
        }

        //入库单状态
        if (!StringUtils.isEmpty(inStockVO.getStatus())) {
            criteria.andEqualTo("status", inStockVO.getStatus());
        }

        //入库时间区间
        if (!StringUtils.isEmpty(inStockVO.getType())) {
            criteria.andBetween("createTime", inStockVO.getStartTime(), inStockVO.getEndTime());
        }

        //进行查询
        List<InStock> inStockList = inStockMapper.selectByExample(example);
        //封装返回数据
        //进行偷天换日
        List<InStockVO> instockVOList = inStockList.stream().map(inStockList1 -> {
            InStockVO vo = new InStockVO();
            BeanUtils.copyProperties(inStockList1, vo);
            Supplier supplier = supplierMapper.selectByPrimaryKey(inStockList1.getSupplierId());
            vo.setSupplierName(supplier.getName());
            vo.setPhone(supplier.getPhone());
            return vo;
        }).collect(Collectors.toList());
        //将数据对象放入到page中，可以计算出总共的数量.(注意当开启分页之后，查询出来的数据其实已经是当前的页的数据了)
        PageInfo<Product> inStockPageInfo = new PageInfo(inStockList);

        System.out.println(inStockPageInfo.getTotal());

        return new PageVO<InStockVO>(inStockPageInfo.getTotal(),   //这个地方的总数量，如果是从pageInfo中拿出来的就是总数居，而不是当前页中数据的数量
                instockVOList);
    }

    //将入库信心移入到回收站
    @Override
    public void remove(Long inStockId) {
        InStock inStock = new InStock();
        inStock.setId(inStockId);
        inStock.setStatus(1);
        inStockMapper.updateByPrimaryKeySelective(inStock);

    }

    //将入库信心从回收站恢复

    @Override
    public void back(Long inStockId) {
        InStock inStock = new InStock();
        inStock.setId(inStockId);
        inStock.setStatus(0);
        inStockMapper.updateByPrimaryKeySelective(inStock);

    }

    //将入库信心删除
    @Override
    public void delete(Long inStockId) {
        //获取iNUm
        InStock inStock = inStockMapper.selectByPrimaryKey(inStockId);
        String inNum = inStock.getInNum();
        //删除info相关关联
        Example example = new Example(InStockInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("inNum",inNum);
        int i = inStockInfoMapper.deleteByExample(example);
        System.out.println("i:"+i);
        //删除instock表下的此数据
        inStockMapper.deleteByPrimaryKey(inStockId);

    }

    @Autowired
    private ProductStockMapper productStockMapper;
    //将物资通过审核
    @Override
    public void publish(Long inStockId) {
        InStock inStock = new InStock();
        inStock.setId(inStockId);
        inStock.setStatus(0);
        inStockMapper.updateByPrimaryKeySelective(inStock);
        //同时更新库存物资数量
        InStock inStock1 = inStockMapper.selectByPrimaryKey(inStockId);
        inStock1.getInNum();
        //获取当前入库号下的商品编号
        Example example = new Example(InStockInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("inNum", inStock1.getInNum());
        List<InStockInfo> inStockInfos = inStockInfoMapper.selectByExample(example);
        //根据商品编号和数量修改库存信息
        inStockInfos.forEach(inStockInfo -> {
            Example example1 = new Example(ProductStock.class);
            example1.createCriteria().andEqualTo("pNum", inStockInfo.getPNum());
            ProductStock productStock = productStockMapper.selectOneByExample(example1);
            if (productStock==null){
                //说明新增的物资商品.之前并不存在。
                productStock.setPNum(inStockInfo.getPNum());
                productStock.setStock(Long.valueOf(inStockInfo.getProductNumber()));
                productStockMapper.insert(productStock);
            }
            productStock.setStock(inStockInfo.getProductNumber() + productStock.getStock());
            productStockMapper.updateByExample(productStock,example1);
        });

    }
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private InStockInfoMapper inStockInfoMapper;
    //添加新的入库信息
    @Override
    public void addIntoStock(InStockVO inStockVO, String username) {

        /*
        * {type: 1, sort: 1, supplierId: "", remark: "122366", address: "河北省/秦皇岛市/长安区",…}
            address: "河北省/秦皇岛市/长安区"
            city: "秦皇岛市"
            contact: "111111111"
            email: "54166556@qq.com"
            name: "123333"
            origin: "长安区"
            phone: "18438004900"
            products: [{productId: 62, productNumber: 2}, {productId: 61, productNumber: 1}]
            province: "河北省"
            remark: "122366"
            sort: 1
            supplierId: ""
            type: 1
            valueCity: "130300"
            valueOrigin: "130302"
            valueProvince: "130000"
        * */
        InStock inStock = new InStock();

        //判断是否新增的来源
        if (inStockVO.getSupplierId() == null) {
            Supplier supplier = new Supplier();
            supplier.setAddress(inStockVO.getAddress());
            supplier.setName(inStockVO.getName());
            supplier.setContact(inStockVO.getContact());
            supplier.setEmail(inStockVO.getEmail());
            supplier.setPhone(inStockVO.getPhone());
            supplier.setSort(inStockVO.getSort());
            supplier.setCreateTime(new Date());
            supplier.setModifiedTime(new Date());
            supplierMapper.insert(supplier);
            System.out.println(supplier);
            //设置提供者id
            inStock.setSupplierId(supplier.getId());
        } else {

            //设置提供者id
            inStock.setSupplierId(inStockVO.getSupplierId());
        }


            Supplier supplier = supplierMapper.selectByPrimaryKey(inStockVO.getSupplierId());

            //设置入库单号
            String uuid = UUID.randomUUID().toString();
            inStock.setInNum(uuid);
            //捐赠类型
            inStock.setType(inStockVO.getType());
            //设置操作员  //TODO 这里应该设置当前用户的名称，现在先将就着admin
            //ok!!!!
            inStock.setOperator(username);
            //创建时间
            inStock.setCreateTime(new Date());
            //修改时间
            inStock.setModified(new Date());
            //捐赠数量(物资总量)
            List<Object> productList = inStockVO.getProducts();
            List<Map<String, Integer>> productListOk = new ArrayList<>();
            for (Object o : productList) {
                String jsonString = JSON.toJSONString(o);
                HashMap<String, Integer> map = JSON.parseObject(jsonString, HashMap.class);
                productListOk.add(map);
            }
//        //进行类型转换
//        List<Map<String, Integer>> productListOk = productList.stream().map(product -> {
//            HashMap<String,Integer> map = JSON.parseObject((String) product, HashMap.class) ;
//            return map;
//        }).collect(Collectors.toList());
//

            Integer productNumberTotal = 0;
            for (Map<String, Integer> map : productListOk) {
                InStockInfo inStockInfo = new InStockInfo();

                //插入到关联表
                inStockInfo.setInNum(inStock.getInNum());
                inStockInfo.setCreateTime(new Date());
                inStockInfo.setModifiedTime(new Date());
                //获取每一个商品的数量
                Integer productNumber = map.get("productNumber");
                productNumberTotal += productNumber;
                //设置关联表中的数据
                inStockInfo.setProductNumber(productNumber);
                //根据productid主键获取product信息
                Product product = productMapper.selectByPrimaryKey(map.get("productId"));
                inStockInfo.setPNum(product.getPNum());
                inStockInfoMapper.insert(inStockInfo);
            }
            //捐赠数量(物资总量)
            inStock.setProductNumber(productNumberTotal);
            //设置默认状态 待审核状态 2
            inStock.setStatus(2);
            //设置备注
            inStock.setRemark(inStockVO.getRemark());
            inStockMapper.insert(inStock);

            System.out.println(inStockVO);
        }

    //获取入库记录明细  （                                                                                                                                                                                                                              ）
    @Override
    public InStockDetailVO detail(Long id, Integer pageNum) {
        InStockDetailVO inStockDetailVO = new InStockDetailVO();
        //获取inNum
        InStock inStock = inStockMapper.selectByPrimaryKey(id);
        String inNum = inStock.getInNum();
        //根据inNum查询inStockInfo数组
        //根据supplierid查询supplier
        Supplier supplier = supplierMapper.selectByPrimaryKey(inStock.getSupplierId());

        Example example = new Example(InStockInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("inNum", inNum);
        PageHelper.startPage(pageNum,3);
        //根据入库单编号查询入库单明细的商品集合
        List<InStockInfo> inStockInfoList = inStockInfoMapper.selectByExample(example);
        //设置inNum
        inStockDetailVO.setInNum(inNum);
        //设置status
        inStockDetailVO.setStatus(inStock.getStatus());
        //设置type
        inStockDetailVO.setType(inStock.getType());
        //设置operator
        inStockDetailVO.setOperator(inStock.getOperator());
        //设置supplierVO
        SupplierVO supplierVO = new SupplierVO();
        BeanUtils.copyProperties(supplier,supplierVO);
        inStockDetailVO.setSupplierVO(supplierVO);

        //设置itemVOS
        //封装对象
        List<InStockItemVO> inStockItemVOS = new ArrayList<>();
        for (InStockInfo inStockInfo : inStockInfoList) {
            //根据物资编号，获取物资的详细信息
            Example example1 = new Example(Product.class);
            Example.Criteria criteria1 = example1.createCriteria();
            criteria1.andEqualTo("pNum", inStockInfo.getPNum());
//            criteria1.andEqualTo("status",0);
            Product product = productMapper.selectOneByExample(example1);
            InStockItemVO inStockItemVO = new InStockItemVO();
            if (product!=null){
                inStockItemVO.setUnit(product.getUnit());
                inStockItemVO.setCount(inStockInfo.getProductNumber());
                inStockItemVO.setId(product.getId());
                inStockItemVO.setImageUrl(product.getImageUrl());
                inStockItemVO.setModel(product.getModel());
                inStockItemVO.setName(product.getName());
                inStockItemVO.setPNum(product.getPNum());
                inStockItemVOS.add(inStockItemVO);
            }

        }
        inStockDetailVO.setItemVOS(inStockItemVOS);


        PageInfo<InStockInfo> inStockDetailVOPageInfo = new PageInfo(inStockInfoList);
        //设置total
        inStockDetailVO.setTotal(inStockDetailVOPageInfo.getTotal());
        return inStockDetailVO;
    }


    //
        //http://www.localhost:8989/business/inStock/addIntoStock
        //{"type":1,"sort":1,"supplierId":"","remark":"122366","address":"河北省/秦皇岛市/长安区",
        // "products":[{"productId":62,"productNumber":2},{"productId":61,"productNumber":1}],
        // "valueProvince":"130000","valueCity":"130300","city":"秦皇岛市","valueOrigin":"130302","origin":"长安区",
        // "province":"河北省","name":"123333","contact":"111111111","email":"54166556@qq.com","phone":"18438004900"}

}
